#!/bin/bash

start_time=$(date +%s)

GIT_HOME_DIR=/home/git

default_IFS=$IFS

repeat() {
    while :
    do
        $@ && return
        sleep 5
    done
}

# 操作仓库文件，不是 git 目录树
# 备份仓库
# git clone --mirror

# 恢复仓库
# git push --mirror

add_repositories() {
    for info in $1
    do
        start=$(date +%s)
        
        index=0
        IFS=";"
        for info_item in $info
        do
            [ $index -eq 0 ] && name=$info_item
            [ $index -eq 1 ] && github_url=$info_item
            let index++
        done
        
        repository_path=$name.git
        whole_repository_path=$(echo "$github_url" | awk -F "github.com/" '{print $2}').git
        author=$(echo "$whole_repository_path" | awk -F "/" '{print $1}')
        
        #echo -e "===========================\n" >> temp
        #echo -e "author ===> $author\n" >> temp
        #echo -e "whole_repository_path ===> $whole_repository_path\n" >> temp
        #echo -e "github_url ===> $github_url\n" >> temp
        #echo -e "===========================\n\n" >> temp

        if [ ! -d $GIT_HOME_DIR/$author ];then
            mkdir -p $GIT_HOME_DIR/$author
        fi
        
        # git clone 失败的情况:
        # 网络问题 ===> 重新运行命令
        # 资源问题，可能是无此资源，可能是资源权限问题
        if [ ! -d $GIT_HOME_DIR/$whole_repository_path ];then
            repeat git clone --mirror $github_url $GIT_HOME_DIR/$whole_repository_path
        fi
        chown -R git:git $GIT_HOME_DIR/$whole_repository_path

        end=$(date +%s)
        echo "备份仓库 $whole_repository_path 的执行时间 => $((end-start))" >> time.log
        #break
    done
}

if [ "$1" == "repositories" ];then
    repositories=$(cat repositories | grep -v "#")
    add_repositories "${repositories[*]}"
elif [ "$1" == "colorscheme_repositories" ];then
    colorschemes=$(cat colorscheme_repositories | grep -v "#")
    add_repositories "${colorschemes[*]}"
elif [ "$1" == "plugin_repositories" ];then
    plugins=$(cat plugin_repositories | grep -v "#")
    add_repositories "${plugins[*]}"
else
    echo "指定参数,repositories,colorscheme_repositories,plugin_repositories!"
fi

end_time=$(date +%s)
echo "执行时间 => $((end-start))" >> time.log

